<template>
  <div class="color-test-container">
    <div class="test-header">
      <h1>🎨 多玩家颜色分配测试</h1>
      <p>测试多人在线涂鸦应用的颜色分配和同步功能</p>
    </div>

    <div class="test-controls">
      <el-button @click="createTestRoom" type="primary" :disabled="isConnected">
        创建测试房间
      </el-button>
      <el-button @click="joinTestRoom" type="success" :disabled="!testRoomCode">
        加入测试房间
      </el-button>
      <el-button @click="addTestPlayer" type="warning" :disabled="!testRoomCode">
        添加测试玩家
      </el-button>
      <el-button @click="clearTestData" type="danger">
        清空测试数据
      </el-button>
    </div>

    <div class="test-status">
      <div class="status-item">
        <span class="label">连接状态:</span>
        <span class="value" :class="{ connected: isConnected }">
          {{ isConnected ? '已连接' : '未连接' }}
        </span>
      </div>
      <div class="status-item">
        <span class="label">测试房间:</span>
        <span class="value">{{ testRoomCode || '未创建' }}</span>
      </div>
      <div class="status-item">
        <span class="label">玩家数量:</span>
        <span class="value">{{ players.length }}</span>
      </div>
    </div>

    <div class="test-content">
      <div class="players-section">
        <h3>玩家列表</h3>
        <div class="players-grid">
          <div
            v-for="(player, index) in players"
            :key="player.id"
            class="player-card"
            :class="{ 'current-player': player.id === currentPlayerId }"
          >
            <div class="player-header">
              <span class="player-index">{{ index + 1 }}</span>
              <span class="player-name">{{ player.nickname }}</span>
            </div>
            <div class="color-display">
              <div class="color-item">
                <span class="color-label">头像:</span>
                <div 
                  class="color-preview avatar" 
                  :style="{ backgroundColor: player.avatarColor || '#cccccc' }"
                ></div>
                <span class="color-value">{{ player.avatarColor || '未设置' }}</span>
              </div>
              <div class="color-item">
                <span class="color-label">画笔:</span>
                <div 
                  class="color-preview brush" 
                  :style="{ backgroundColor: player.brushColor || '#cccccc' }"
                ></div>
                <span class="color-value">{{ player.brushColor || '未设置' }}</span>
              </div>
            </div>
            <div class="player-info">
              <span class="player-id">ID: {{ player.id }}</span>
              <span class="player-owner" v-if="player.isOwner">房主</span>
            </div>
          </div>
        </div>
      </div>

      <div class="debug-section">
        <h3>调试信息</h3>
        <div class="debug-controls">
          <el-button @click="checkColorConsistency" size="small" type="info">
            检查颜色一致性
          </el-button>
          <el-button @click="generateColorReport" size="small" type="success">
            生成颜色报告
          </el-button>
          <el-button @click="exportDebugData" size="small" type="warning">
            导出调试数据
          </el-button>
        </div>
        
        <div class="debug-output">
          <h4>调试输出:</h4>
          <div class="debug-content">
            <pre>{{ debugOutput }}</pre>
          </div>
        </div>
      </div>
    </div>

    <div class="test-actions">
      <h3>测试动作</h3>
      <div class="action-buttons">
        <el-button @click="simulatePaintAction" type="primary">
          模拟涂色动作
        </el-button>
        <el-button @click="simulatePlayerJoin" type="success">
          模拟玩家加入
        </el-button>
        <el-button @click="simulatePlayerLeave" type="warning">
          模拟玩家离开
        </el-button>
        <el-button @click="testColorSync" type="info">
          测试颜色同步
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useGameStore } from '@/stores/game'
import { createSignalRService } from '@/services/socketService'
import { ElMessage } from 'element-plus'
import { logColorEvent, checkColors, getColorReport } from '@/utils/colorDebugger'

const gameStore = useGameStore()
const signalRService = createSignalRService(gameStore)

// 测试状态
const testRoomCode = ref('')
const testRoomName = ref('颜色测试房间')
const debugOutput = ref('')
const testPlayerCounter = ref(1)

// 计算属性
const isConnected = computed(() => gameStore.isConnected)
const players = computed(() => gameStore.players)
const currentPlayerId = computed(() => gameStore.currentPlayer?.id)

// 测试方法
function createTestRoom() {
  const roomCode = `TEST_${Date.now().toString(36).toUpperCase()}`
  testRoomCode.value = roomCode
  
  try {
    signalRService.createRoom(roomCode, testRoomName.value, 6, '', 'test-host', '测试房主')
    ElMessage.success(`测试房间已创建: ${roomCode}`)
    logColorEvent('testRoomCreated', { roomCode, roomName: testRoomName.value })
  } catch (error) {
    ElMessage.error('创建测试房间失败: ' + error.message)
  }
}

function joinTestRoom() {
  if (!testRoomCode.value) {
    ElMessage.warning('请先创建测试房间')
    return
  }
  
  const playerId = `test-player-${testPlayerCounter.value++}`
  const nickname = `测试玩家${testPlayerCounter.value - 1}`
  
  try {
    signalRService.joinRoom(testRoomCode.value, playerId, nickname)
    ElMessage.success(`已加入测试房间: ${nickname}`)
    logColorEvent('testPlayerJoined', { roomCode: testRoomCode.value, playerId, nickname })
  } catch (error) {
    ElMessage.error('加入测试房间失败: ' + error.message)
  }
}

function addTestPlayer() {
  if (!testRoomCode.value) {
    ElMessage.warning('请先创建测试房间')
    return
  }
  
  // 模拟添加测试玩家到store
  const playerId = `test-player-${testPlayerCounter.value++}`
  const nickname = `测试玩家${testPlayerCounter.value - 1}`
  
  // 生成随机颜色（模拟后端分配）
  const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD']
  const randomColor = colors[Math.floor(Math.random() * colors.length)]
  
  const testPlayer = {
    id: playerId,
    nickname,
    avatarColor: randomColor,
    brushColor: randomColor,
    color: randomColor,
    joinedAt: Date.now(),
    isOwner: false
  }
  
  gameStore.addPlayer(testPlayer)
  ElMessage.success(`测试玩家已添加: ${nickname}`)
  logColorEvent('testPlayerAdded', testPlayer)
}

function clearTestData() {
  testRoomCode.value = ''
  testPlayerCounter.value = 1
  gameStore.clearRoom()
  debugOutput.value = ''
  ElMessage.success('测试数据已清空')
}

function checkColorConsistency() {
  const result = checkColors(players.value)
  const output = `颜色一致性检查结果:\n${JSON.stringify(result, null, 2)}`
  debugOutput.value = output
  
  if (result.isValid) {
    ElMessage.success('颜色一致性检查通过！')
  } else {
    ElMessage.warning(`发现 ${result.issues.length} 个颜色问题`)
  }
  
  logColorEvent('colorConsistencyCheck', result)
}

function generateColorReport() {
  const report = getColorReport(players.value, gameStore.currentPlayer)
  const output = `颜色分配报告:\n${JSON.stringify(report, null, 2)}`
  debugOutput.value = output
  
  ElMessage.success('颜色报告已生成')
  logColorEvent('colorReportGenerated', report)
}

function exportDebugData() {
  const data = {
    timestamp: new Date().toISOString(),
    roomCode: testRoomCode.value,
    players: players.value,
    currentPlayer: gameStore.currentPlayer,
    colorReport: getColorReport(players.value, gameStore.currentPlayer)
  }
  
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `color_test_debug_${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.json`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
  
  ElMessage.success('调试数据已导出')
  logColorEvent('debugDataExported', { dataSize: JSON.stringify(data).length })
}

function simulatePaintAction() {
  if (!testRoomCode.value || players.value.length === 0) {
    ElMessage.warning('请先创建房间并添加玩家')
    return
  }
  
  const currentPlayer = gameStore.currentPlayer
  if (!currentPlayer) {
    ElMessage.warning('当前玩家未设置')
    return
  }
  
  try {
    const paintData = {
      x: Math.floor(Math.random() * 800),
      y: Math.floor(Math.random() * 600),
      color: currentPlayer.brushColor || currentPlayer.color || '#000000',
      brushSize: 12,
      tool: 'brush'
    }
    
    signalRService.sendPaintActionWithData(
      testRoomCode.value,
      currentPlayer.id,
      paintData
    )
    
    ElMessage.success('模拟涂色动作已发送')
    logColorEvent('simulatedPaintAction', paintData)
  } catch (error) {
    ElMessage.error('发送涂色动作失败: ' + error.message)
  }
}

function simulatePlayerJoin() {
  addTestPlayer()
}

function simulatePlayerLeave() {
  if (players.value.length === 0) {
    ElMessage.warning('没有玩家可以移除')
    return
  }
  
  const lastPlayer = players.value[players.value.length - 1]
  gameStore.removePlayer(lastPlayer.id)
  ElMessage.success(`玩家已移除: ${lastPlayer.nickname}`)
  logColorEvent('testPlayerRemoved', lastPlayer)
}

function testColorSync() {
  const currentPlayer = gameStore.currentPlayer
  if (!currentPlayer) {
    ElMessage.warning('当前玩家未设置')
    return
  }
  
  // 检查颜色同步状态
  const playerInList = players.value.find(p => p.id === currentPlayer.id)
  const syncStatus = {
    currentPlayer: {
      id: currentPlayer.id,
      nickname: currentPlayer.nickname,
      avatarColor: currentPlayer.avatarColor,
      brushColor: currentPlayer.brushColor,
      color: currentPlayer.color
    },
    playerInList: playerInList ? {
      id: playerInList.id,
      nickname: playerInList.nickname,
      avatarColor: playerInList.avatarColor,
      brushColor: playerInList.brushColor,
      color: playerInList.color
    } : null,
    isSynced: playerInList && 
              currentPlayer.avatarColor === playerInList.avatarColor &&
              currentPlayer.brushColor === playerInList.brushColor
  }
  
  const output = `颜色同步测试结果:\n${JSON.stringify(syncStatus, null, 2)}`
  debugOutput.value = output
  
  if (syncStatus.isSynced) {
    ElMessage.success('颜色同步正常！')
  } else {
    ElMessage.warning('颜色同步存在问题')
  }
  
  logColorEvent('colorSyncTest', syncStatus)
}

// 组件挂载时初始化
onMounted(() => {
  logColorEvent('colorTestPageMounted', { timestamp: new Date().toISOString() })
})
</script>

<style scoped>
.color-test-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.test-header {
  text-align: center;
  margin-bottom: 30px;
}

.test-header h1 {
  color: #333;
  margin-bottom: 10px;
}

.test-header p {
  color: #666;
  font-size: 16px;
}

.test-controls {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.test-status {
  display: flex;
  justify-content: center;
  gap: 30px;
  margin-bottom: 30px;
  flex-wrap: wrap;
}

.status-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.status-item .label {
  font-size: 12px;
  color: #666;
}

.status-item .value {
  font-weight: 600;
  color: #333;
}

.status-item .value.connected {
  color: #52c41a;
}

.test-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  margin-bottom: 30px;
}

.players-section,
.debug-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.players-section h3,
.debug-section h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 10px;
}

.players-grid {
  display: grid;
  gap: 15px;
}

.player-card {
  border: 2px solid #f0f0f0;
  border-radius: 8px;
  padding: 15px;
  background: #fafafa;
  transition: all 0.3s ease;
}

.player-card:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.player-card.current-player {
  border-color: #1890ff;
  background: #e6f7ff;
}

.player-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
}

.player-index {
  width: 24px;
  height: 24px;
  background: #1890ff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: bold;
}

.player-name {
  font-weight: 600;
  color: #333;
}

.color-display {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-bottom: 15px;
}

.color-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.color-label {
  font-size: 12px;
  color: #666;
  min-width: 40px;
}

.color-preview {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 2px solid white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.color-value {
  font-size: 12px;
  color: #333;
  font-family: monospace;
}

.player-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.player-owner {
  background: #52c41a;
  color: white;
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 10px;
}

.debug-controls {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.debug-output {
  background: #f5f5f5;
  border-radius: 8px;
  padding: 15px;
}

.debug-output h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #333;
}

.debug-content {
  max-height: 300px;
  overflow-y: auto;
}

.debug-content pre {
  margin: 0;
  font-size: 12px;
  color: #333;
  white-space: pre-wrap;
  word-break: break-all;
}

.test-actions {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.test-actions h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 10px;
}

.action-buttons {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

@media (max-width: 768px) {
  .test-content {
    grid-template-columns: 1fr;
  }
  
  .test-controls,
  .action-buttons {
    flex-direction: column;
  }
  
  .test-status {
    flex-direction: column;
    gap: 15px;
  }
}
</style>
